package com.whh.utils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class StrUtils {
	
	private static final byte[] DES_KEY = { 21, 1, -110, 82, -32, -85, -128, -65 };

	private static final String KEY = "abcdef0123456789";
	
	private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
	
	public static Boolean isBlank(String rdpNo) {
		if(rdpNo==null) return true;
		if("".equals(rdpNo)) return true;
		if("null".equals(rdpNo.toLowerCase())) return true;
		if("undefined".equals(rdpNo.toLowerCase())) return true;
		return false;
	}
	public static Boolean isNotBlank(String rdpNo) {
		return !isBlank(rdpNo);
	}
	public static Integer toInteger(Object obj) {
		if(obj==null)
			return null;
		if(obj instanceof String) 
			return Integer.valueOf(String.valueOf(obj));
		if(obj instanceof Integer)
			return (Integer) obj;
		return null;
	}
	public static String toStr(Object obj) {
		if(obj==null) return null;
		
		if(obj instanceof Date) return DateUtils.toStr((Date)obj);
		return String.valueOf(obj);
	}
	public static Boolean isEqual(String source,String dest) {
		if(isBlank(source)||isBlank(dest))
			return Boolean.FALSE;
		Boolean b = source.equals(dest);
		return b;
	}
	public static Boolean isNotEqual(String source,String dest) {
		return !isEqual(source,dest);
	}
	public static String getFirstPinyin(String text) {
		if(isBlank(text)) return "";
		
		String pinyinStr = "";
		char[] newChar = text.toCharArray();
		HanyuPinyinOutputFormat hpof = new HanyuPinyinOutputFormat();
		hpof.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		hpof.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for(int i=0; i<newChar.length; i++) {
			if(newChar[i] >128) {
				try {
					pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], hpof)[0].charAt(0);
				}catch(BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			}else {
				pinyinStr += newChar[i];
			}
		}
		return pinyinStr;
	}
	public static String getPinyin(String text) {
		if(isBlank(text)) return "";
		
		String pinyinStr = "";
		char[] newChar = text.toCharArray();
		HanyuPinyinOutputFormat hpof = new HanyuPinyinOutputFormat();
		hpof.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		hpof.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for(int i=0; i<newChar.length; i++) {
			if(newChar[i] >128) {
				try {
					pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], hpof)[0];
				}catch(BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			}else {
				pinyinStr += newChar[i];
			}
		}
		return pinyinStr;
	}
	public static String parse(Object obj) {
		if(obj==null)
			return null;
		if(obj instanceof String)
			return String.valueOf(obj);
		if(obj instanceof Integer)
			return String.valueOf(obj);
		return null;
	}
	public static String getDbCode(String dbUrl) {
		if(isBlank(dbUrl)) return null;
		int a = dbUrl.lastIndexOf("/");
		int b = dbUrl.indexOf("?");
		if(a>0&&b>0) return dbUrl.substring(a+1, b);
		return null;
	}
	/**
     *  EDS的加密解密代码
     */
	public static String encryptByDes(String data) {
    	String encryptedData = null;
    	try {
    		// DES算法要求有一个可信任的随机数源
    		SecureRandom sr = new SecureRandom();
    		DESKeySpec deskey = new DESKeySpec(DES_KEY);
    		// 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
    		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    		SecretKey key = keyFactory.generateSecret(deskey);
    		// 加密对象
    		Cipher cipher = Cipher.getInstance("DES");
    		cipher.init(Cipher.ENCRYPT_MODE, key, sr);
    		// 加密，并把字节数组编码成字符串
    		encryptedData = Base64.encodeBase64String(cipher.doFinal(data.getBytes()));
    	} catch (Exception e) {
    		// log.error("加密错误，错误信息：", e);
    		throw new RuntimeException("加密错误，错误信息：", e);
    	}
    	return encryptedData;
    }
    public static String decryptByDes(String cryptData) {
    	String decryptedData = null;
    	try {
    		// DES算法要求有一个可信任的随机数源
    		SecureRandom sr = new SecureRandom();
    		DESKeySpec deskey = new DESKeySpec(DES_KEY);
    		// 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
    		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    		SecretKey key = keyFactory.generateSecret(deskey);
    		// 解密对象
    		Cipher cipher = Cipher.getInstance("DES");
    		cipher.init(Cipher.DECRYPT_MODE, key, sr);
    		// 把字符串进行解码，解码为为字节数组，并解密
    		decryptedData = new String(cipher.doFinal(Base64.decodeBase64(cryptData)));
    	} catch (Exception e) {
    		throw new RuntimeException("解密错误，错误信息：", e);
    	}
    	return decryptedData;
    }
    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */ 
    public static String encryptByAes(String content){ 
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128); 
	    	Cipher cipher = Cipher.getInstance(ALGORITHMSTR); 
	    	cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES")); 
	    	byte[] b = cipher.doFinal(content.getBytes("utf-8")); 
	    	return Base64.encodeBase64String(b); 
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    	return content; 
    } 
    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */ 
    public static String decryptByAes(String encryptStr){ 
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128); 
	    	Cipher cipher = Cipher.getInstance(ALGORITHMSTR); 
	    	cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES")); 
	    	byte[] encryptBytes = Base64.decodeBase64(encryptStr); 
	    	byte[] decryptBytes = cipher.doFinal(encryptBytes); 
	    	return new String(decryptBytes); 
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    	return encryptStr;
    }
    public static String md5Encrypt(String str) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes());
			byte b[] = md5.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			return "";
		}
	}
    
    public static byte[] byteMerger(byte[] byte_1, byte[] byte_2){
    	byte[] byte_3 = new byte[byte_1.length+byte_2.length];
    	System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
    	System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
    	return byte_3;
    }
    /** 下划线转驼峰 */
    public static String lineToHump(String str) {
    	Pattern linePattern = Pattern.compile("_(\\w)");
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    /** 驼峰转下划线 */
    public static String humpToLine(String str) {
    	Pattern humpPattern = Pattern.compile("[A-Z]");
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
      	while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
  //首字母大写
    public static String upperCaseFirst(String text) {
        char[] cs = text.toCharArray();
        cs[0]-=32;
        return String.valueOf(cs);
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	

}
